package zdh.avatar.gui;

import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import zdh.avatar.*;
import zdh.avatar.base.*;

/**
 *
 * @author Gem Seeker
 */
@SuppressWarnings("serial")
public class SetButtonChild extends JFrame implements ActionListener {

    private MainFrame main;
    private AvatarConfig config;
    private ElementButton selectedButton;
    private ArrayList<ElementButton> availableButtons;
    private ArrayList<ElementButton> selectedButtons;

    public SetButtonChild(MainFrame main, AvatarConfig config, ElementButton button) {
        this.main = main;
        this.config = config;

        selectedButton = button;
        availableButtons = new ArrayList<>();
        selectedButtons = new ArrayList<>();

        initComponents();
        setComponents();
        initListeners();
        
        this.getRootPane().setDefaultButton(btn_save);
    }

    private void setComponents() {
        ElementPanel[] panels = ElementLoader.getElementPanels(config.getElementsPath() + "panels/");

        // add panels to combo box
        if (panels != null) {
            for (ElementPanel p : panels) {
                cb_panels.addItem(p);
            }
        }

        selectedButtons = selectedButton.getChildButtons();
        System.out.println(selectedButtons);

        if (selectedButtons != null || selectedButtons.size() > 0) {
            lst_childBtns.setModel(new ModelButtonList(selectedButtons.toArray(new ElementButton[selectedButtons.size()])));
        }

        lst_childBtns.repaint();

        // load buttons of selected panel (ignore those that are already selected)
        ElementPanel panel = (ElementPanel) cb_panels.getSelectedItem();
        fillList1(panel);
    }

    private void initListeners() {
        btn_add.addActionListener(this);
        btn_remove.addActionListener(this);
        btn_save.addActionListener(this);
        btn_cancel.addActionListener(this);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        main.setEnabled(true);
                    }
                });
            }
        });

        cb_panels.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (cb_panels.getItemCount() == 0) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            btn_add.setEnabled(false);
                            btn_remove.setEnabled(false);
                        }
                    });
                }
                ElementPanel panel = (ElementPanel) cb_panels.getSelectedItem();
                fillList1(panel);
            }
        });

        lst_buttons.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!lst_buttons.isSelectionEmpty()) {
                    lst_childBtns.clearSelection();
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            btn_add.setEnabled(true);
                        }
                    });
                } else {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            btn_add.setEnabled(false);
                        }
                    });
                }
            }
        });

        lst_childBtns.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!lst_childBtns.isSelectionEmpty()) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            lst_buttons.clearSelection();
                            btn_remove.setEnabled(true);
                        }
                    });
                } else {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            btn_remove.setEnabled(false);
                        }
                    });
                }
            }
        });
    }

    private void fillList1(ElementPanel panel) {
        ElementButton[] buttons = ElementLoader.getElementButtons(config.getElementsPath() + "buttons/");

        // clear list...
        availableButtons.clear();

        // filter buttons... buttons of selected panel are only allowed, also
        // ignore the current selected button itself
        if (buttons != null) {
            for (int i = 0; i < buttons.length; i++) {
                if (buttons[i].getPanelName().equals(panel.getPanelName())) {

                    boolean available = true;
                    if (buttons[i].getButtonName().equals(selectedButton.getButtonName())) {
                        available = false;
                    }

                    if (selectedButtons.size() > 0) {
                        for (int x = 0; x < selectedButtons.size(); x++) {
                            if (selectedButtons.get(x).getButtonName().equals(buttons[i].getButtonName())) {
                                available = false;
//                                System.out.println(buttons[i].toString() + " is already selected.");
                            }
                        }
                    }

                    if (available) {
//                        System.out.println("Adding " + buttons[i].toString() + " to list 1.");
                        availableButtons.add(buttons[i]);
                    }
                }
            }
        }

        lst_buttons.setModel(
                new ModelButtonList(
                availableButtons.toArray(
                new ElementButton[availableButtons.size()])));

        lst_buttons.repaint();
    }

    private void reloadList1() {
        lst_buttons.setModel(
                new ModelButtonList(
                availableButtons.toArray(
                new ElementButton[availableButtons.size()])));

        lst_buttons.repaint();
    }

    private void fillList2() {
        lst_childBtns.setModel(
                new ModelButtonList(
                selectedButtons.toArray(
                new ElementButton[selectedButtons.size()])));

        lst_childBtns.repaint();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();

        if (source == btn_add) {
            ElementButton b = (ElementButton) ((ModelButtonList) lst_buttons.getModel())
                    .getButton(lst_buttons.getSelectedIndex());

            selectedButtons.add(b);
            availableButtons.remove(b);

            reloadList1();
            fillList2();

        } else if (source == btn_remove) {
            ElementButton b = (ElementButton) ((ModelButtonList) lst_childBtns.getModel())
                    .getButton(lst_childBtns.getSelectedIndex());

            availableButtons.add(b);
            selectedButtons.remove(b);

            reloadList1();
            fillList2();

        } else if (source == btn_save) {
            ElementButton newButton = new ElementButton(selectedButton.getButtonName(),
                    selectedButton.getButtonColor(), selectedButton.getAudioPaths(),
                    selectedButton.getPanelName(), selectedButton.getButtonIndex());

            for(ElementButton b:selectedButtons){
                newButton.addChildButton(b);
            }
//            newButton.addChildButtons(selectedButtons);

            ElementLoader.replaceElementButton(selectedButton,
                    newButton,
                    config.getElementsPath() + "buttons/");

            System.out.println(newButton.getChildButtons().toString());

            main.reload();
            closeWindow();
        } else if (source == btn_cancel) {
            closeWindow();
        }
    }

    public void showWindow() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                main.setEnabled(false);
                setLocationRelativeTo(main);
                setVisible(true);
            }
        });
    }

    public void closeWindow() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                main.setEnabled(true);
                dispose();
            }
        });
    }

    // <editor-fold defaultstate="collapsed" desc="Generated by NetBeans">
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        lst_buttons = new javax.swing.JList();
        cb_panels = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        lst_childBtns = new javax.swing.JList();
        lbl_childButtons = new javax.swing.JLabel();
        btn_add = new javax.swing.JButton();
        btn_remove = new javax.swing.JButton();
        btn_save = new javax.swing.JButton();
        btn_cancel = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Set next button(s)");
        setResizable(false);

        lst_buttons.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(lst_buttons);

        lst_childBtns.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(lst_childBtns);

        lbl_childButtons.setText("Next Recommended Button(s)");

        btn_add.setText(">>>");
        btn_add.setEnabled(false);

        btn_remove.setText("<<<");
        btn_remove.setEnabled(false);

        btn_save.setText("Save");

        btn_cancel.setText("Cancel");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cb_panels, 0, 173, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btn_add, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btn_remove, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbl_childButtons, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btn_save, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btn_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbl_childButtons)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(98, 98, 98)
                                .addComponent(btn_add)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_remove))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cb_panels, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_save)
                    .addComponent(btn_cancel))
                .addGap(15, 15, 15))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_add;
    private javax.swing.JButton btn_cancel;
    private javax.swing.JButton btn_remove;
    private javax.swing.JButton btn_save;
    private javax.swing.JComboBox cb_panels;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lbl_childButtons;
    private javax.swing.JList lst_buttons;
    private javax.swing.JList lst_childBtns;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>
}
